#!/bin/bash

source /home/shell/util.sh

function elastic-install () {
    download /opt/elasticsearch.tar.gz https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.15.0-linux-x86_64.tar.gz
    tar -xf /opt/elasticsearch.tar.gz -C /opt/
    rm -rf /opt/elasticsearch.tar.gz
    mv /opt/elasticsearch-* /opt/elasticsearch
}

function elastic-config () {
    useradd elasticsearch
    mkdir -p /var/run/elasticsearch
    # 修改配置
    cp /opt/elasticsearch/config/elasticsearch.yml /opt/elasticsearch/config/elasticsearch.yml.bak
    echo "action.auto_create_index: .monitoring*,.watches,.triggered_watches,.watcher-history*,.ml*" >> /opt/elasticsearch/config/elasticsearch.yml
    sed -i "s/#network.host: 192.168.0.1/network.host: 0.0.0.0/g" /opt/elasticsearch/config/elasticsearch.yml
    sed -i "s/#http.port: 9200/http.port: 9200/" /opt/elasticsearch/config/elasticsearch.yml
    sed -i "s/#node.name: node-1/node.name: node-1/" /opt/elasticsearch/config/elasticsearch.yml
    sed -i 's/#cluster.initial_master_nodes: \["node-1", "node-2"\]/cluster.initial_master_nodes: \["node-1"\]/g' /opt/elasticsearch/config/elasticsearch.yml
## 新增配置
tee -a /opt/elasticsearch/config/elasticsearch.yml<<EOF
http.cors.enabled: true
http.cors.allow-origin: "*"
http.cors.allow-headers: Authorization
xpack.security.enabled: true
xpack.security.transport.ssl.enabled: true
xpack.security.transport.ssl.verification_mode: certificate
xpack.security.transport.ssl.keystore.path: certs/elastic-certificates.p12
xpack.security.transport.ssl.truststore.path: certs/elastic-certificates.p12
EOF
    # 生成CA
    /opt/elasticsearch/bin/elasticsearch-certutil ca
    # 签发证书
    /opt/elasticsearch/bin/elasticsearch-certutil cert --ca elastic-stack-ca.p12
    # 移动证书
    mkdir -p /opt/elasticsearch/config/certs
    mv /opt/elasticsearch/elastic-certificates.p12 /opt/elasticsearch/config/certs/
    mv /opt/elasticsearch/elastic-stack-ca.p12 /opt/elasticsearch/config/certs/
    chown elasticsearch:elasticsearch -R /opt/elasticsearch/
    chown elasticsearch:elasticsearch -R /var/run/elasticsearch

    firewall-addport 9300
    firewall-addport 9200

tee /etc/sysctl.conf -a<<EOF
vm.max_map_count=262144
EOF
    sysctl -p
}

function elastic-mkservice () {
tee /etc/systemd/system/elasticsearch.service<<EOF
[Unit]
Description=Elasticsearch
Documentation=https://www.elastic.co
Wants=network-online.target
After=network-online.target

[Service]
Type=notify
RuntimeDirectory=elasticsearch
PrivateTmp=true
Environment=ES_HOME=/opt/elasticsearch
Environment=ES_PATH_CONF=/opt/elasticsearch/config
Environment=PID_DIR=/var/run/elasticsearch
Environment=ES_SD_NOTIFY=true
EnvironmentFile=-/etc/default/elasticsearch

WorkingDirectory=/opt/elasticsearch

User=elasticsearch
Group=elasticsearch

ExecStart=/opt/elasticsearch/bin/elasticsearch -p /var/run/elasticsearch/elasticsearch.pid --quiet

# StandardOutput is configured to redirect to journalctl since
# some error messages may be logged in standard output before
# elasticsearch logging system is initialized. Elasticsearch
# stores its logs in /var/log/elasticsearch and does not use
# journalctl by default. If you also want to enable journalctl
# logging, you can simply remove the "quiet" option from ExecStart.
StandardOutput=journal
StandardError=inherit

# Specifies the maximum file descriptor number that can be opened by this process
LimitNOFILE=65535

# Specifies the maximum number of processes
LimitNPROC=4096

# Specifies the maximum size of virtual memory
LimitAS=infinity

# Specifies the maximum file size
LimitFSIZE=infinity

# Disable timeout logic and wait until process is stopped
TimeoutStopSec=0

# SIGTERM signal is used to stop the Java process
KillSignal=SIGTERM

# Send the signal only to the JVM rather than its control group
KillMode=process

# Java process is never killed
SendSIGKILL=no

# When a JVM receives a SIGTERM signal it exits with code 143
SuccessExitStatus=143

# Allow a slow startup before the systemd notifier module kicks in to extend the timeout
TimeoutStartSec=75

[Install]
WantedBy=multi-user.target

# Built for packages-7.15.0 (packages)

EOF
    # 服务启动
    systemctl daemon-reload
    systemctl enable --now elasticsearch
    # 设置密码
    /opt/elasticsearch/bin/elasticsearch-setup-passwords auto -b > /tmp/elasticsearch-passwd
}

function analysis-install () {
    # 安装插件
    ## 中文分词插件
    while [ true ]; do
        curl -sL https://hub.fastgit.org/medcl/elasticsearch-analysis-ik/releases|grep -e "elasticsearch-analysis-ik-"|grep span|perl -pe "s/.*elasticsearch-analysis-ik-(.*)\.zip.*/\1/g"
        read -p "请选择elasticsearch-analysis-ik版本：" version
        if [[ -z "${version}" ]]; then
        printFail "请输入版本"
        else
        break;
        fi
    done
    # https://hub.fastgit.org/medcl/elasticsearch-analysis-ik/releases/download/v${version}/elasticsearch-analysis-ik-${version}.zip
    # https://ghproxy.com/https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v${version}/elasticsearch-analysis-ik-${version}.zip

    /opt/elasticsearch/bin/elasticsearch-plugin install -b https://ghproxy.com/https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v${version}/elasticsearch-analysis-ik-${version}.zip
}

function kibana_install () {
    # 安装UI管理界面
    download /opt/kibana.tar.gz https://artifacts.elastic.co/downloads/kibana/kibana-${version}-linux-x86_64.tar.gz
    tar -zxf /opt/kibana.tar.gz -C /opt
    rm -rf /opt/kibana.tar.gz
    mv /opt/kibana-*-linux-x86_64 /opt/kibana
}

function kibana_config () {
    ## 配置
    kibana_system_passwd=`grep "PASSWORD kibana_system" /tmp/elasticsearch-passwd|awk '{print $4}'`

    cp /opt/kibana/config/kibana.yml /opt/kibana/config/kibana.yml.bak
    sed -i "s/#server.publicBaseUrl: \"\"/server.publicBaseUrl: \"https:\/\/"$host_addr":5601\"/g" /opt/kibana/config/kibana.yml
    sed -i "s/#server.port: 5601/server.port: 5601/g" /opt/kibana/config/kibana.yml
    sed -i 's/#server.host: "localhost"/server.host: "0.0.0.0"/g' /opt/kibana/config/kibana.yml
    sed -i 's#\#elasticsearch.hosts: \["http://localhost:9200"\]#elasticsearch.hosts: ["http://127.0.0.1:9200"]#g' /opt/kibana/config/kibana.yml
    sed -i 's/#kibana.index: ".kibana"/kibana.index: ".kibana"/g' /opt/kibana/config/kibana.yml
    sed -i 's/#i18n.locale: "en"/i18n.locale: "zh-CN"/g' /opt/kibana/config/kibana.yml
    sed -i 's/#elasticsearch.username: "kibana_system"/elasticsearch.username: "kibana_system"/g' /opt/kibana/config/kibana.yml
    sed -i 's/#elasticsearch.password: "pass"/elasticsearch.password: "'$kibana_system_passwd'"/g' /opt/kibana/config/kibana.yml
    echo -e "`/opt/kibana/bin/kibana-encryption-keys generate --force|tail -n 4`" >> /opt/kibana/config/kibana.yml

# curl用户名密码配置
tee ~/.netrc<<EOF
machine localhost
login elastic
password `grep "PASSWORD elastic" /tmp/elasticsearch-passwd|awk '{print $4}'`  
EOF

    # 日志
    mkdir -p /var/log/webapps/kibana/

    firewall-addport 5601

bash /home/shell/serviced-install.sh<<EOF
1
1

kibana
/opt/kibana/bin/kibana --allow-root -l /var/log/webapps/kibana/standard.out




EOF
}


elastic-install && elastic-config
elastic-mkservice
# analysis-install

# kibana_install && kibana_config

sleep 3s

printInfo "====================安装信息===================="
printInfo "kibana日志: /var/log/webapps/kibana/standard.out"
printInfo "elasticsearch日志: /opt/elasticsearch/logs/elasticsearch.log"
printInfo "kibana: http://$host_addr:5601/"
printInfo "elasticsearch: http://$host_addr:9200/"
printInfo "用户名1: elastic"
printInfo "密码1: `grep "PASSWORD elastic" /tmp/elasticsearch-passwd|awk '{print $4}'`"
printInfo "用户名2: kibana_system"
printInfo "密码2: `grep "PASSWORD kibana_system" /tmp/elasticsearch-passwd|awk '{print $4}'`"
printInfo "用户名3: remote_monitoring_user"
printInfo "密码3: `grep "PASSWORD remote_monitoring_user" /tmp/elasticsearch-passwd|awk '{print $4}'`"
printInfo "用户名4: apm_system"
printInfo "密码4: `grep "PASSWORD apm_system" /tmp/elasticsearch-passwd|awk '{print $4}'`"
printInfo "用户名5: logstash_system"
printInfo "密码5: `grep "PASSWORD logstash_system" /tmp/elasticsearch-passwd|awk '{print $4}'`"
printInfo "用户名6: beats_system"
printInfo "密码6: `grep "PASSWORD beats_system" /tmp/elasticsearch-passwd|awk '{print $4}'`"
printInfo "====================安装信息===================="